#include "common.h"
#include <pthread.h>

#define MAX_LINE 4096

char rot13_char(char c)
{
    if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M'))
        return c + 13;
    else if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z'))
        return c - 13;
    else
        return c;
}

// 子线程
void *thread_run(void *arg)
{
    pthread_detach(pthread_self()); // 线程从父线程分离
    int fd = (int)arg;

    char outbuf[MAX_LINE + 1];
    size_t outbuf_used = 0;
    ssize_t result;
    while (1)
    {
        char ch;
        result = recv(fd, &ch, 1, 0); // 每次接受一个字符
        if (result == 0)
        {
            break; // 没有数据了，直接 break
        }
        else if (result == -1)
        {
            perror("read");
            break; // 读取失败，直接 break
        }
        if (outbuf_used < sizeof(outbuf))
        {
            outbuf[outbuf_used++] = rot13_char(ch);
        }
        // 遇到换行
        // 读取客户端发送的数据，待读完一行后，再向客户端发送
        if (ch == '\n')
        {
            send(fd, outbuf, outbuf_used, 0); // 发送数据
            outbuf_used = 0;
            continue;
        }
    }
}

int main(int argc, char const *argv[])
{
    int port = 3000;
    int listener_fd = tcp_server_listen(port);
    printf("listening at localhost:%d\n", port);

    pthread_t tid;

    while (1)
    {
        struct sockaddr_storage ss;
        socklen_t slen = sizeof(ss);
        int fd = accept(listener_fd, (struct sockaddr *)&ss, &slen);
        if (fd < 0)
        {
            perror("accept!");
        }
        else
        {
            pthread_create(&tid, NULL, thread_run, (void *)fd); // 新建线程处理连接
        }
    }

    return 0;
}
